
# SensorModel.rb
# Tells the fighter what's going on.

module SensorModel

  # Sensor's basic skeleton.
  def question?(condition, yes, no)
    lambda{
      if condition
        yes.call
      else
        no.call
      end
    }
  end

  def a_then_b(action_a, action_b)
    lambda{
      action_a.call
      action_b.call
    }
  end

  def init(action)
    action.call
  end

  # Sensor's questions.
  def enemy_on_sight?(yes, no)
    question?(track_enemy, yes, no)
  end

  # Sensor's conditions.
  def track_enemy
    tank = $player
    return if (@pos_x - tank.pos_x) == 0
    
    offset_x_minus = @pos_x + Gosu::offset_x(@angle - 5, 5)
    offset_y_minus = @pos_y + Gosu::offset_y(@angle - 5, 5)
    offset_x_plus  = @pos_x + Gosu::offset_x(@angle + 5, 5)
    offset_y_plus  = @pos_y + Gosu::offset_y(@angle + 5, 5)

    a_plus  = Gosu::distance(@pos_x, @pos_y, offset_x_plus, offset_y_plus)
    a_minus = Gosu::distance(@pos_x, @pos_y, offset_x_minus, offset_y_minus)
    b_plus  = Gosu::distance(offset_x_plus, offset_y_plus, tank.pos_x, tank.pos_y)
    b_minus = Gosu::distance(offset_x_minus, offset_y_minus, tank.pos_x, tank.pos_y)
    c       = Gosu::distance(@pos_x, @pos_y, tank.pos_x, tank.pos_y)
    
    angle_plus  = Math.acos(((a_plus ** 2) + (c ** 2) - (b_plus ** 2)) / (2 * a_plus * c))
    angle_minus = Math.acos(((a_minus ** 2) + (c ** 2) - (b_minus ** 2)) / (2 * a_minus * c))

    return angle_minus > angle_plus 
  end

end
